#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]){

    int ret = 0;
    int fd;
    char readbuf[10], writebuf[50];
    static char userdata[] = {"helloa"};

    if(argc != 3){
      printf("ERROR USAGE!\r\n");
      return -1;
    }
    
    char* filename;
    filename = argv[1];

    fd = open(filename, O_RDWR);

    if(fd < 0){
      printf("cant open file %s\r\n", filename);
      return -1;
    }

    if(atoi(argv[2]) == 1){ // 读
        ret =  read(fd, readbuf, sizeof(readbuf));
        if(ret < 0){
          printf("read file %s failed\r\n", filename);
          return -1;
        }else{
          printf("RERAD DATA: %s\r\n", readbuf);
        }
    }

 
    if(atoi(argv[2]) == 2){ // 读

        memcpy(writebuf, userdata, sizeof(userdata));
        ret = write(fd, writebuf, sizeof(userdata));
        if(ret < 0){
          printf("write file %s failed!\r\n", filename);
        }
    }

    close(fd);

    return 0;
}